package com.catcoin.deposit.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.catcoin.deposit.model.Account;
import com.catcoin.deposit.model.Inviteid;
import com.catcoin.deposit.model.User;
import com.catcoin.deposit.result.AppResult;
import com.catcoin.deposit.result.Result;
import com.catcoin.deposit.service.IAccountService;
import com.catcoin.deposit.service.IInviteidService;
import com.catcoin.deposit.service.ISmsService;
import com.catcoin.deposit.service.IUserService;
import com.catcoin.deposit.util.CacheUtil;
import com.catcoin.deposit.util.MD5Util;
import com.catcoin.deposit.util.MSGUtil;
import com.catcoin.deposit.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author caody
 * @since 2018-08-31
 */
@RestController
@CrossOrigin
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IInviteidService iInviteidService;
    @Autowired
    private ISmsService smsService;
    @Autowired
    private CacheUtil cacheUtil;


    @RequestMapping("/getString")
    public Object  getString(){
        return userService.selectById(1);
    }

    /**
     * 用户登录
     * @param userphone 手机号
     * @param password  密码
     * @return
     */
    @RequestMapping("/login")
    public AppResult login(String userphone,String password){
        Map<String, Object> resultMap = userService.login(userphone, password);
        if ("00".equals(resultMap.get("code").toString())){
            return AppResult.ERROR(resultMap.get("msg").toString());

        }else {
            return   AppResult.OK(resultMap.get("user"));
        }
    }

    /**
     * 注册
     * @param loginName 用户名
     * @param num 短信验证码
     * @param userPhone 用户手机号
     * @param checkData 分享人信息（有可能是空，说明没有分享人）
     * @param loginPwd 登录密码
     * @param password_confirm 二次登录密码
     * @return
     */
    @RequestMapping("/regist")
    public AppResult regist( String loginName, String num,  String userPhone,  String checkData,  String loginPwd,  String password_confirm) {
        if (!loginPwd.equals(password_confirm)) {
            return AppResult.ERROR("两次密码输入不一致", -3);
        }
        Map<String, Object> map = userService.regist(loginName, num, userPhone, checkData, loginPwd);
        if("00".equals(map.get("code").toString())){
            return AppResult.ERROR(map.get("msg").toString());
        }
        return AppResult.OK(map.get("user"));
    }

    /**
     * 验证分享人信息
     * @param checkData
     * @return
     */
    @RequestMapping("/checkShare")
    public AppResult findShare( String checkData) {
        Map<String, Object> map =userService.findShare(checkData);
        return AppResult.OK( map);
    }

    /**
     *获取用户账户
     * @param userId
     * @return
     */
    @RequestMapping("/getBalnce")
    public AppResult getBalnce(String userId){
        Map<String, Object> resultMap = userService.getBalnce(userId);
        if ("00".equals(resultMap.get("code").toString())){
            return   AppResult.ERROR(resultMap.get("msg").toString());
        }else{
            return AppResult.OK(resultMap);
        }
    }

    /**
     * 发送短信验证码（zy）
     * @param userPhone
     * @param type  请求短信时该手机是否已经注册（1:未注册；2：已注册）
     * @param request
     * @return
     */
    @RequestMapping("/getCheckCode")
    @ResponseBody
    public  AppResult siteGetMessageCode(String userPhone,String type,HttpServletRequest request){
        boolean responsePhone = MSGUtil.getResponsePhone(userPhone);
        if (!responsePhone){
            return  AppResult.ERROR("手机号不正确",-5);
        }
        User u = new User();
        u.setUserPhone(userPhone);
        EntityWrapper<User> ew = new EntityWrapper<User>(u);
        User user=userService.selectOne(ew);
        if("1".equals(type)){
            if(!StringUtils.isBlank(user)){
                return AppResult.ERROR("该手机号码已经存在",-4);
            }
        }
        if("2".equals(type)){
            if(StringUtils.isEmpty(user)){
                return AppResult.ERROR("该手机号码尚未注册",-3);
            }
        }
        /*String templateCode="";
        String code = MSGUtil.getCode();
        String messageCode=code;
        if (sendCode=="modifyPhone"){
            templateCode="SMS_119092823";
        }
        if(sendCode=="register"){
            templateCode="SMS_119077955";
        }
        if(sendCode=="findLoginPwd"){
            templateCode="SMS_119077952";
        }
        if (sendCode=="findPayPwd"){
            templateCode="SMS_119083003";
        }*/
        try {
            HashMap<String,Object> map = (HashMap<String,Object>)smsService.send_register_message(userPhone);
            String cod = map.get("code").toString();
            if (cod.equals("isv.BUSINESS_LIMIT_CONTROL")){
                return AppResult.ERROR("手机号发送频繁，请稍后再试",-1);
            }
            if (!cod.equals("OK")){
                return AppResult.ERROR("该手机号今天短信发送量已达上限，请明天再试",-1);
            }
            return AppResult.OK("发送成功",map.get("num").toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AppResult.ERROR("服务器异常",-1);
        }

    }
    @RequestMapping("/loginBycode")
    public AppResult loginBycode(String userphone, String num){
        Map<String,Object> resultMap=userService.loginBycode(userphone,num);
        if ("00".equals(resultMap.get("code").toString())){
            return AppResult.ERROR(resultMap.get("msg").toString());
        }else {
            return   AppResult.OK(resultMap.get("user"));
        }
    }

    @RequestMapping("/deleteUser")
    @ResponseBody
    public  AppResult deleteUser(String userId){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(userId);
        if(!isNum.matches()){
            return AppResult.ERROR("查询不到用户信息");
        }
        int userId2 = Integer.parseInt(userId);
        User user = new User();
        user.setUserId(userId2);
        EntityWrapper<User> ew = new EntityWrapper<User>(user);
        boolean delete = userService.delete(ew);
        Account account = new Account();
        account.setUserId(userId2);
        EntityWrapper<Account> ew2 = new EntityWrapper<Account>(account);
        accountService.delete(ew2);
        Inviteid inviteid = new Inviteid();
        inviteid.setUserId(userId2);
        EntityWrapper<Inviteid> ew3 = new EntityWrapper<Inviteid>(inviteid);
        iInviteidService.delete(ew3);
        return AppResult.OK("成功");
    }

    /**
     * 图片上传阿里云
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/aliyunUpload")
    @ResponseBody
    public AppResult upload(HttpServletRequest request) {
        Map<String, Object> map = userService.upload(request);
        if("00".equals(map.get("code").toString())){
            return AppResult.ERROR(map.get("msg").toString());
        }
        return AppResult.OK(map);
    }

    /**
     *
     * 修改登录密码
     *
     * @param userId
     * @param oldPwd
     * @param newPwd
     * @param password_confirm
     * @return
     */
    @RequestMapping("/modifyPwd")
    @ResponseBody
    public AppResult updateLoginPwd(String userId ,String oldPwd,String newPwd,String password_confirm) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(userId);
        if(!isNum.matches()){
            return AppResult.ERROR("查询不到用户信息");
        }
        User user = userService.selectById(userId);
        if(user == null){
            return AppResult.ERROR("查询不到用户信息");
        }
        String userLoginPwd = oldPwd + String.valueOf(user.getSalt());
        String encrypt = MD5Util.encrypt(userLoginPwd);
        if (!user.getPassword().equals(encrypt)) {
            return AppResult.ERROR("原密码不正确", -1);
        }
        if (!newPwd.equals(password_confirm)) {
            return AppResult.ERROR("两次输入密码不一致请重新输入", -1);
        }
        String userNewPwd = newPwd + String.valueOf(user.getSalt());
        user.setPassword(MD5Util.encrypt(userNewPwd));
        boolean update = userService.updateById(user);
        if (update) {
            return AppResult.OK("修改成功",null);
        }
        if (!update) {
            return AppResult.ERROR("修改失败", -1);
        }
        return AppResult.ERROR("修改失败", -1);
    }

    /**
     *
     * 忘记密码 找回密码
     *
     * @param userId 用户id
     * @param num 验证码
     * @param newPwd 新密码
     * @param password_confirm 二次确认密码
     * @param userphone 手机号
     * @return
     */
    @RequestMapping("/retrievePwd")
    @ResponseBody
    public AppResult usersRetrievePwd(String userId,String num,String newPwd, String password_confirm, String userphone) {
        User user = new User();
        user.setUserPhone(userphone);
        EntityWrapper<User> ew = new EntityWrapper<User>(user);
        User user2 = userService.selectOne(ew);
        if(user2 == null){
            return AppResult.ERROR("查询不到用户信息");
        }
        if(userId!=null && !userId.equals("")){
            if(user2.getUserId()!=Integer.parseInt(userId)){
                return  AppResult.ERROR("请使用用户自己的手机号");
            }
        }

        if (!newPwd.equals(password_confirm)) {
            return AppResult.ERROR("两次密码输入不一致请重新输入", -1);
        }
        Object obj = cacheUtil.get("mb:"+userphone);
        if(obj == null){
            return AppResult.ERROR("短息验证码失效");
        }
        if(!obj.toString().equals(num)){
            return AppResult.ERROR("短信验证码错误");
        }
        //       Integer code1 = Integer.parseInt(cacheUtil.get(userPhone).toString());
//        if (!sendCode.equals(code1)){
//            return AppResult.ERROR("短信验证码输入错误", -1);
//        }
//        if (Integer.parseInt(sendCode) != code1) {
//            return AppResult.ERROR("短信验证码输入错误", -1);
//        }
        if (!user2.getUserPhone().equals(userphone)){
            return AppResult.ERROR("请使用用户自己的手机号",-1);
        }
        User user3 = new User();
        user3.setUserId(user2.getUserId());
        user3.setPassword(MD5Util.encrypt(newPwd + user2.getSalt()));
        boolean update = userService.updateById(user3);
        if (update) {
            return AppResult.OK("修改成功", null);
        }
        return AppResult.ERROR("修改失败", -1);
    }

    /**
     *
     * 修改资料
     *
     * @param userId
     * @return
     */
    @RequestMapping("/updatePersonalData")
    @ResponseBody
    public AppResult usersRetrievePwd(String userId,HttpServletRequest request) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(userId);
        if(!isNum.matches()){
            return AppResult.ERROR("查询不到用户信息");
        }
        AppResult upload = upload(request);
        Object data = upload.getData();
        String userPhoto = null;
        if(data != null){
            Map<String,Object> map = (HashMap<String,Object>)data;
            String code = map.get("code").toString();
            if("00".equals(code)){
                return AppResult.ERROR(map.get("msg").toString(),null);
            }
            userPhoto = map.get("url").toString();
        }
        User user = new User();
        user.setUserId(Integer.parseInt(userId));
        Boolean b = false;
        if(userPhoto != null && !"".equals(userPhoto)){
            user.setUserPhoto(userPhoto);
            b = true;
        }
        User user1 = userService.selectById(userId);
        if(b){
            boolean b2 = userService.updateById(user);
            if(b2){
                return AppResult.OK("成功",user1.getUserPhoto());
            }
            return AppResult.ERROR("修改失败",null);
        }
        return AppResult.OK("成功",user1.getUserPhoto());
    }

    /**
     *
     * 修改支付密码
     *
     * @param userId
     * @param oldPayPwd
     * @param newPayPwd
     * @param password_confirm
     * @return
     */
    @RequestMapping("/modifyPayPwd")
    @ResponseBody
    public AppResult updatePayPwd(String userId ,String oldPayPwd,String newPayPwd,String password_confirm) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(userId);
        if(!isNum.matches()){
            return AppResult.ERROR("查询不到用户信息");
        }
        User user = userService.selectById(userId);
        if(user == null){
            return AppResult.ERROR("查询不到用户信息");
        }
        String userPayPwd = oldPayPwd + String.valueOf(user.getSalt());
        String encrypt = MD5Util.encrypt(userPayPwd);
        if (!user.getPayPwd().equals(encrypt)) {
            return AppResult.ERROR("原支付密码不正确", -1);
        }
        if (!newPayPwd.equals(password_confirm)) {
            return AppResult.ERROR("两次输入支付密码不一致请重新输入", -1);
        }
        String userNewPayPwd = newPayPwd + String.valueOf(user.getSalt());
        user.setPayPwd(MD5Util.encrypt(userNewPayPwd));
        boolean update = userService.updateById(user);
        if (update) {
            return AppResult.OK("修改成功",null);
        }
        if (!update) {
            return AppResult.ERROR("修改失败", -1);
        }
        return AppResult.ERROR("修改失败", -1);
    }

    /**
     *
     * 忘记支付密码 找回支付密码
     *
     * @param userId 用户id
     * @param num 验证码
     * @param newPayPwd 新密码
     * @param password_confirm 二次确认密码
     * @param userphone 手机号
     * @return
     */
    @RequestMapping("/retrievePayPwd")
    @ResponseBody
    public AppResult usersRetrievePayPwd(String userId, String num,String newPayPwd, String password_confirm, String userphone) {
        User user = new User();
        user.setUserPhone(userphone);
        EntityWrapper<User> ew = new EntityWrapper<User>(user);
        User user2 = userService.selectOne(ew);
        if(user2 == null){
            return AppResult.ERROR("查询不到用户信息");
        }
        if(user2.getUserId() != Integer.parseInt(userId)){
            return AppResult.ERROR("请使用用户自己的手机号");
        }
        if (!newPayPwd.equals(password_confirm)) {
            return AppResult.ERROR("两次密码输入不一致请重新输入", -1);
        }
        Object obj = cacheUtil.get("mb:"+userphone);
        if(obj == null){
            return AppResult.ERROR("短息验证码失效");
        }
        if(!obj.toString().equals(num)){
            return AppResult.ERROR("短信验证码错误");
        }
        //       Integer code1 = Integer.parseInt(cacheUtil.get(userPhone).toString());
//        if (!sendCode.equals(code1)){
//            return AppResult.ERROR("短信验证码输入错误", -1);
//        }
//        if (Integer.parseInt(sendCode) != code1) {
//            return AppResult.ERROR("短信验证码输入错误", -1);
//        }
        if (!user2.getUserPhone().equals(userphone)){
            return AppResult.ERROR("请使用用户自己的手机号",-1);
        }
        User user4 = new User();
        user4.setUserId(user2.getUserId());
        user4.setPayPwd(MD5Util.encrypt(newPayPwd + user2.getSalt()));
        boolean update = userService.updateById(user4);
        if (update) {
            return AppResult.OK("修改成功", null);
        }
        return AppResult.ERROR("修改失败", -1);
    }

    /**
     *
     * 设置支付密码
     *
     * @param userId
     * @param newPayPwd
     * @param password_confirm
     * @return
     */
    @RequestMapping("/setPayPwd")
    @ResponseBody
    public AppResult usersSetPayPwd(String userId,String newPayPwd, String password_confirm) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(userId);
        if(!isNum.matches()){
            return AppResult.ERROR("查询不到用户信息");
        }
        User user2 = userService.selectById(userId);
        if(user2 == null){
            return AppResult.ERROR("查询不到用户信息");
        }
        if (!newPayPwd.equals(password_confirm)) {
            return AppResult.ERROR("两次密码输入不一致请重新输入", -1);
        }
        User user = userService.selectById(userId);
        String encrypt = newPayPwd + user.getSalt();
        String payPwd = MD5Util.encrypt(encrypt);
        user.setPayPwd(payPwd);
        boolean b = userService.updateById(user);
        if(b){
            return AppResult.OK("成功",null);
        }
        return AppResult.ERROR("修改失败",null);
    }



    /**
     * 推荐好友生成二维码
     *
     * @author wangang
     *
     */
    @RequestMapping(value = "/qrcode", method = RequestMethod.GET)
    @ResponseBody
    public AppResult qrcode(HttpServletRequest request, HttpServletResponse response) {
        String urlLong = "http:/localhost:8763/qrcode?userId=";
        String userId = request.getParameter("userId");
        String allUrl=null;
        try {
            allUrl = urlLong+userId;
        } catch (Exception e) {
            e.printStackTrace();
            return AppResult.ERROR("生成二维码错误");
        }
        return AppResult.OK(allUrl);
    }

    /**
     * 推荐人信息（谁推荐我）
     * @author wangang
     */
    @RequestMapping(value = "/recommendInfo", method = RequestMethod.GET)
    @ResponseBody
    public AppResult recommendInfo(String userId) {
        User user = null;
        try {
            user = userService.recommendInfo(userId);
            if(user==null){
                return AppResult.ERROR("未查到推荐人信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AppResult.ERROR("系统错误");
        }
        return AppResult.OK(user);
    }

    /**
     * 推荐人信息（谁推荐我）
     * @author wangang
     */
    @RequestMapping(value = "/recommendList", method = RequestMethod.GET)
    @ResponseBody
    public AppResult recommendList(String userId) {
        List<User>  listUser = null;
        try {
            listUser = userService.recommendList(Integer.parseInt(userId));
            if(listUser.size()==0){
                return AppResult.ERROR("未查到推荐人列表信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AppResult.ERROR("系统错误");
        }
        return AppResult.OK(listUser);
    }

    /**
     * 推荐人信息（我推荐的人列表）分页
     * @author wangang
     */
    @RequestMapping(value = "/recommendListNew", method = RequestMethod.GET)
    @ResponseBody
    public AppResult recommendListNew( String userId, String pageNum) {
        Integer pageSize = 10;
        PageHelper.startPage(Integer.parseInt(pageNum),pageSize);
        List<Map<String,Object>> list = userService.recommendListNew(Integer.parseInt(userId));
        PageInfo<Map<String,Object>> info = new PageInfo<>(list);
        Integer totalPages = info.getPages();
        return  AppResult.OK(totalPages,"success",list);
    }

    /**
     * 推荐人信息（我推荐的人列表）分页 数量
     * @author wangang
     */
    @RequestMapping(value = "/recommendListCount", method = RequestMethod.GET)
    @ResponseBody
    public AppResult recommendListCount( String userId) {
        Integer num = userService.recommendListCount(Integer.parseInt(userId));
        return  AppResult.OK("success",num);
    }

    /**
     * 获取用户服务协议内容
     * @author wangang
     */
    @RequestMapping(value = "/getUserProtocol", method = RequestMethod.GET)
    @ResponseBody
    public AppResult getUserProtocol() {
        String content =null;
        //String content = userService.getUserProtocol();
        return  AppResult.OK("success",content);
    }


}

